<template>
  <div class="banner-list">
    <!-- 操作栏 -->
    <el-card class="operation-card">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        添加轮播图
      </el-button>
    </el-card>

    <!-- 轮播图列表 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column label="轮播图" width="200">
          <template #default="{ row }">
            <img 
              :src="'http://127.0.0.1:8080/file/'+row.img" 
              fit="cover"
              style="width: 150px; height: 80px"
            />
          </template>
        </el-table-column>
        <el-table-column prop="goodName" label="标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="img" label="链接" min-width="200" show-overflow-tooltip />
        <el-table-column prop="showOrder" label="排序" width="100" align="center" />
        <el-table-column align="center" label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button type="danger" link @click="handleDelete(row)">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="添加轮播图"
      width="600px">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px">
        <el-form-item label="商品id" prop="goodId">
          <el-input v-model="form.goodId" placeholder="请输入商品id" />
        </el-form-item>
        <el-form-item label="标题" prop="goodName">
          <el-input v-model="form.goodName" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="图片" prop="img">
          <el-upload
            class="banner-upload"
            :show-file-list="false"
            :http-request="customUpload"
            :before-upload="beforeUpload">
            <el-image
              v-if="form.img || form.previewUrl"
              :src="form.previewUrl||'http:127.0.0.1:8080/file/'+form.img"
              fit="cover"
              class="upload-image"
            />
            <el-icon v-else class="upload-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">建议尺寸：800x400像素，支持jpg、png格式</div>
        </el-form-item>
        <el-form-item label="排序" prop="showOrder">
          <el-input-number v-model="form.showOrder" :min="0" :max="99" />
        </el-form-item>
        
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import { getBannerListAPI } from '@/api/banner'
import { uploadFileAPI } from '@/api/file'
import { deleteBannerAPI, saveBannerAPI } from '../../../api/banner'
const loading = ref(false)
const tableData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

const dialogVisible = ref(false)
const dialogType = ref('add')
const submitLoading = ref(false)
const formRef = ref(null)

const form = reactive({
  goodId:'',
  goodName: '',
  img: '',
  previewUrl:'',
  showOrder:0,

})

const rules = {
  goodName: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { max: 50, message: '标题最多50个字符', trigger: 'blur' }
  ],
  img: [
    { required: true, message: '请上传轮播图', trigger: 'change' }
  ],
  
  showOrder: [
    { required: true, message: '请输入排序号', trigger: 'blur' }
  ]
}

// 自定义上传方法
const customUpload = async (options) => {
  try {
    const formData = new FormData()
    formData.append('file', options.file)
    const res = await uploadFileAPI(formData)
    console.log(res);
    if(res.code !== '200') {
      ElMessage.error(res.msg||'上传失败')
      form.previewUrl = ''
      return
    }
    form.img = res.data
    ElMessage.success('上传成功')
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('上传失败')
    form.previewUrl = ''
  }
}

// 获取轮播图列表
const getBannerList = async () => {
  // loading.value = true
  try {
    const res = await getBannerListAPI()
    console.log(res);
    
    if(res.code!=='200'){
      ElMessage.error(res.msg)
      loading.value = false
      return
    }
    tableData.value = res.data
    console.log(tableData.value);
    
    
    total.value = res.data.total
  } catch (error) {
    console.log('获取轮播图列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 添加轮播图
const handleAdd = () => {
  dialogType.value = 'add'
  Object.keys(form).forEach(key => {
    form[key] = key === 'status' ? 1 : (key === 'sort' ? 0 : '')
  })
  dialogVisible.value = true
}

// 编辑轮播图
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.keys(form).forEach(key => {
    form[key] = row[key]
  })
  dialogVisible.value = true
}

// 删除轮播图
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除该轮播图吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
     const res = await deleteBannerAPI(row.id)
      console.log(res);
      ElMessage.success('删除成功')
      getBannerList()
    } catch (error) {
      console.error('删除轮播图失败:', error)
    }
  }).catch(() => {})
}



// 上传前校验
const beforeUpload = (file) => {
  const isImage = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传jpg/png格式的图片！')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB！')
    return false
  }
    // 创建本地预览URL
    form.previewUrl = URL.createObjectURL(file)
  return true
}


// 提交表单
const handleSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        const res = await saveBannerAPI(form)
        console.log(res);
        dialogVisible.value = false
        getBannerList()
      } catch (error) {
        console.error(error)
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getBannerList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getBannerList()
}

onMounted(() => {
  getBannerList()
})
</script>

<style scoped>
.banner-list {
  .operation-card {
    margin-bottom: 20px;
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .banner-upload {
    :deep(.el-upload) {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);

      &:hover {
        border-color: var(--el-color-primary);
      }
    }

    .upload-image {
      width: 300px;
      height: 150px;
      display: block;
    }

    .upload-icon {
      font-size: 28px;
      color: #8c939d;
      width: 300px;
      height: 150px;
      line-height: 150px;
      text-align: center;
    }
  }

  .upload-tip {
    font-size: 12px;
    color: #999;
    margin-top: 5px;
  }
}
</style> 